// https://aws.amazon.com/cn/s3/getting-started/
const fs = require('fs')
const mime = require('mime')
const { S3Client, PutObjectCommand } = require('@aws-sdk/client-s3')
const log = require('../log')
const packageJson = require('../package.json')

const UP = {}

// 检验必填配置项
UP.check = (options) => {
  log.yellow(`[${packageJson.name}] CDN >> Amazon S3 ...`)
  let isError = false
  if (!options.accessKeyId) {
    isError = true
    log.red(`[${packageJson.name}] accessKeyId not found in options.s3`)
  }
  if (!options.secretAccessKey) {
    isError = true
    log.red(`[${packageJson.name}] secretAccessKey not found in options.s3`)
  }
  if (!options.Bucket) {
    isError = true
    log.red(`[${packageJson.name}] Bucket not found in options.s3`)
  }
  if (!options.region) {
    isError = true
    log.red(`[${packageJson.name}] region not found in options.s3`)
  }
  if (isError) {
    return false
  }
  return true
}

/**
 * 上传
 * @param {String} uploadPath 上传路径
 * @param {String} localPath 本地文件路径
 * @param {Object} options 配置项 accessKeyId, secretAccessKey, Bucket, region
 */
UP.put = async(uploadPath, localPath, options) => {
  // 上传
  const client = await new S3Client({
    region: options.region,
    credentials:  {  
      accessKeyId: options.accessKeyId,
      secretAccessKey: options.secretAccessKey,
    }
  })
  try {
    const data = await client.send(new PutObjectCommand({
      Bucket: options.Bucket,
      Body: fs.createReadStream(localPath),
      Key: uploadPath,
      ContentType: mime.getType(uploadPath)
    }))
    log.green(`Upload Success => ${uploadPath}`)
    return null
  } catch (error) {
    log.red(`[${packageJson.name}] Upload Error => ${uploadPath}`)
    return error
  }
}

module.exports = UP
